"""
QMainWindow 中使用 QTabWidget 添加多个子窗口示例
基于 PySide6 实现
支持无边框窗口、窗口拉伸、自定义标题栏按钮
"""
import sys
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QTabWidget, QWidget, 
    QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
    QTextEdit, QLineEdit, QTableWidget, QTableWidgetItem,
    QSpinBox, QStatusBar
)
from PySide6.QtCore import Qt, QPoint, QRect
from PySide6.QtGui import QIcon, QCursor


class FirstTabWidget(QWidget):
    """第一个标签页 - 欢迎页面"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)
        
        # 标题
        title = QLabel("欢迎页面")
        title.setStyleSheet("font-size: 24px; font-weight: bold; color: #2c3e50;")
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 描述文本
        desc = QLabel("这是第一个标签页，展示基本信息和简单交互")
        desc.setAlignment(Qt.AlignmentFlag.AlignCenter)
        desc.setStyleSheet("font-size: 14px; color: #7f8c8d; margin: 10px;")
        
        # 输入框
        self.input_field = QLineEdit()
        self.input_field.setPlaceholderText("在这里输入内容...")
        self.input_field.setMaximumWidth(400)
        
        # 按钮
        self.submit_btn = QPushButton("提交")
        self.submit_btn.setMaximumWidth(200)
        self.submit_btn.clicked.connect(self.on_submit)
        
        # 结果显示
        self.result_label = QLabel("")
        self.result_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.result_label.setStyleSheet("color: #27ae60; font-weight: bold; font-size: 16px;")
        
        # 添加组件到布局
        layout.addStretch()
        layout.addWidget(title)
        layout.addWidget(desc)
        layout.addWidget(self.input_field, alignment=Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.submit_btn, alignment=Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.result_label)
        layout.addStretch()
    
    def on_submit(self):
        """提交按钮点击事件"""
        text = self.input_field.text()
        if text:
            self.result_label.setText(f"✅ 已提交: {text}")
            self.input_field.clear()
        else:
            self.result_label.setText("⚠️ 请输入内容")


class SecondTabWidget(QWidget):
    """第二个标签页 - 文本编辑器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        
        # 标题
        title = QLabel("文本编辑器")
        title.setStyleSheet("font-size: 20px; font-weight: bold; color: #34495e;")
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        btn_clear = QPushButton("清空")
        btn_clear.clicked.connect(self.clear_text)
        
        btn_load = QPushButton("加载示例")
        btn_load.clicked.connect(self.load_sample)
        
        btn_copy = QPushButton("复制全部")
        btn_copy.clicked.connect(self.copy_all)
        
        toolbar_layout.addWidget(btn_clear)
        toolbar_layout.addWidget(btn_load)
        toolbar_layout.addWidget(btn_copy)
        toolbar_layout.addStretch()
        
        # 文本编辑器
        self.text_edit = QTextEdit()
        self.text_edit.setPlaceholderText("在这里编写文本...")
        
        # 字数统计
        self.char_count_label = QLabel("字符数: 0")
        self.char_count_label.setStyleSheet("color: #95a5a6;")
        self.text_edit.textChanged.connect(self.update_char_count)
        
        # 布局组装
        layout.addWidget(title)
        layout.addLayout(toolbar_layout)
        layout.addWidget(self.text_edit)
        layout.addWidget(self.char_count_label)
    
    def clear_text(self):
        """清空文本"""
        self.text_edit.clear()
    
    def load_sample(self):
        """加载示例文本"""
        sample_text = """这是一段示例文本。

QTabWidget 是 Qt 中用于创建标签页界面的控件。
它可以包含多个子窗口，用户可以通过点击标签来切换不同的页面。

主要特性：
1. 支持多个标签页
2. 可以动态添加/移除标签
3. 支持图标显示
4. 可以设置标签位置（顶部、底部、左侧、右侧）
5. 支持可关闭标签"""
        self.text_edit.setPlainText(sample_text)
    
    def copy_all(self):
        """复制全部文本到剪贴板"""
        self.text_edit.selectAll()
        self.text_edit.copy()
        self.char_count_label.setText("✅ 已复制到剪贴板")
    
    def update_char_count(self):
        """更新字符统计"""
        count = len(self.text_edit.toPlainText())
        self.char_count_label.setText(f"字符数: {count}")


class ThirdTabWidget(QWidget):
    """第三个标签页 - 数据表格"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        
        # 标题
        title = QLabel("数据表格")
        title.setStyleSheet("font-size: 20px; font-weight: bold; color: #34495e;")
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        btn_add_row = QPushButton("添加行")
        btn_add_row.clicked.connect(self.add_row)
        
        btn_remove_row = QPushButton("删除选中行")
        btn_remove_row.clicked.connect(self.remove_row)
        
        btn_clear = QPushButton("清空表格")
        btn_clear.clicked.connect(self.clear_table)
        
        toolbar_layout.addWidget(btn_add_row)
        toolbar_layout.addWidget(btn_remove_row)
        toolbar_layout.addWidget(btn_clear)
        toolbar_layout.addStretch()
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(["ID", "名称", "数量", "价格"])
        self.table.setAlternatingRowColors(True)
        
        # 状态栏（先创建）
        self.status_label = QLabel("总行数: 0")
        self.status_label.setStyleSheet("color: #7f8c8d;")
        
        # 初始化数据（在status_label创建之后）
        self.init_table_data()
        
        # 布局组装
        layout.addWidget(title)
        layout.addLayout(toolbar_layout)
        layout.addWidget(self.table)
        layout.addWidget(self.status_label)
    
    def init_table_data(self):
        """初始化表格数据"""
        data = [
            ["1", "笔记本", "10", "4500.00"],
            ["2", "鼠标", "25", "89.00"],
            ["3", "键盘", "15", "299.00"],
            ["4", "显示器", "8", "1899.00"],
            ["5", "耳机", "20", "199.00"],
        ]
        
        self.table.setRowCount(len(data))
        for row, row_data in enumerate(data):
            for col, value in enumerate(row_data):
                item = QTableWidgetItem(value)
                if col == 0:  # ID列设置为只读
                    item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                self.table.setItem(row, col, item)
        
        self.update_status()
    
    def add_row(self):
        """添加新行"""
        row_count = self.table.rowCount()
        self.table.insertRow(row_count)
        
        # 设置ID
        new_id = str(row_count + 1)
        id_item = QTableWidgetItem(new_id)
        id_item.setFlags(id_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
        self.table.setItem(row_count, 0, id_item)
        
        # 设置默认值
        self.table.setItem(row_count, 1, QTableWidgetItem("新商品"))
        self.table.setItem(row_count, 2, QTableWidgetItem("0"))
        self.table.setItem(row_count, 3, QTableWidgetItem("0.00"))
        
        self.update_status()
    
    def remove_row(self):
        """删除选中行"""
        current_row = self.table.currentRow()
        if current_row >= 0:
            self.table.removeRow(current_row)
            self.update_status()
    
    def clear_table(self):
        """清空表格"""
        self.table.setRowCount(0)
        self.update_status()
    
    def update_status(self):
        """更新状态信息"""
        self.status_label.setText(f"总行数: {self.table.rowCount()}")


class MainWindow(QMainWindow):
    """主窗口 - 包含QTabWidget，无边框设计"""
    
    def __init__(self):
        super().__init__()
        
        # 用于窗口拖动和拉伸
        self.drag_position = QPoint()
        self.resize_edge = None
        self.resizing = False
        self.resize_margin = 5  # 拉伸边距
        
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        # 设置无边框窗口
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False)
        
        self.setWindowTitle("QTabWidget 多标签页示例")
        self.setGeometry(100, 100, 900, 600)
        
        # 主容器
        main_container = QWidget()
        self.setCentralWidget(main_container)
        container_layout = QVBoxLayout(main_container)
        container_layout.setContentsMargins(0, 0, 0, 0)
        container_layout.setSpacing(0)
        
        # 创建自定义标题栏（包含TabBar和窗口控制按钮）
        title_bar = self.create_title_bar()
        container_layout.addWidget(title_bar)
        
        # 创建中心QTabWidget
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.TabPosition.North)
        self.tab_widget.setMovable(True)
        
        # 隐藏TabWidget自带的TabBar（我们用自定义的）
        self.tab_widget.tabBar().hide()
        
        container_layout.addWidget(self.tab_widget)
        
        # 创建三个标签页
        self.first_tab = FirstTabWidget()
        self.second_tab = SecondTabWidget()
        self.third_tab = ThirdTabWidget()
        
        # 添加标签页到QTabWidget
        self.tab_widget.addTab(self.first_tab, "欢迎")
        self.tab_widget.addTab(self.second_tab, "编辑器")
        self.tab_widget.addTab(self.third_tab, "数据表格")
        
        # 连接标签切换信号
        self.tab_widget.currentChanged.connect(self.on_tab_changed)
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
        
        # 设置样式
        self.set_style()
        
        # 启用鼠标追踪（用于拉伸窗口）
        self.setMouseTracking(True)
    
    def create_title_bar(self):
        """创建自定义标题栏（包含TabBar和窗口控制按钮）"""
        title_bar = QWidget()
        title_bar.setFixedHeight(40)
        title_bar.setObjectName("titleBar")
        title_bar_layout = QHBoxLayout(title_bar)
        title_bar_layout.setContentsMargins(5, 0, 5, 0)
        title_bar_layout.setSpacing(0)
        
        # 应用图标和标题
        title_label = QLabel("📑 QTabWidget 示例")
        title_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #2c3e50; padding-left: 10px;")
        title_bar_layout.addWidget(title_label)
        
        # 添加标签页按钮
        self.tab_buttons = []
        tab_names = ["欢迎", "编辑器", "数据表格"]
        
        for i, name in enumerate(tab_names):
            btn = QPushButton(name)
            btn.setCheckable(True)
            btn.setObjectName("tabButton")
            btn.clicked.connect(lambda checked, idx=i: self.switch_tab(idx))
            self.tab_buttons.append(btn)
            title_bar_layout.addWidget(btn)
        
        # 默认选中第一个
        self.tab_buttons[0].setChecked(True)
        
        title_bar_layout.addStretch()
        
        # 窗口控制按钮
        # 最小化按钮
        btn_minimize = QPushButton("—")
        btn_minimize.setObjectName("minimizeButton")
        btn_minimize.setFixedSize(40, 40)
        btn_minimize.clicked.connect(self.showMinimized)
        
        # 最大化/还原按钮
        self.btn_maximize = QPushButton("□")
        self.btn_maximize.setObjectName("maximizeButton")
        self.btn_maximize.setFixedSize(40, 40)
        self.btn_maximize.clicked.connect(self.toggle_maximize)
        
        # 关闭按钮
        btn_close = QPushButton("✕")
        btn_close.setObjectName("closeButton")
        btn_close.setFixedSize(40, 40)
        btn_close.clicked.connect(self.close)
        
        title_bar_layout.addWidget(btn_minimize)
        title_bar_layout.addWidget(self.btn_maximize)
        title_bar_layout.addWidget(btn_close)
        
        return title_bar
    
    def switch_tab(self, index):
        """切换标签页"""
        self.tab_widget.setCurrentIndex(index)
        
        # 更新按钮状态
        for i, btn in enumerate(self.tab_buttons):
            btn.setChecked(i == index)
    
    def toggle_maximize(self):
        """切换最大化/还原"""
        if self.isMaximized():
            self.showNormal()
            self.btn_maximize.setText("□")
        else:
            self.showMaximized()
            self.btn_maximize.setText("❐")
    
    def mousePressEvent(self, event):
        """鼠标按下事件 - 用于拖动窗口和开始拉伸"""
        if event.button() == Qt.MouseButton.LeftButton:
            # 判断是否在边缘（用于拉伸）
            edge = self.get_resize_edge(event.position().toPoint())
            if edge and not self.isMaximized():
                self.resizing = True
                self.resize_edge = edge
                self.drag_position = event.globalPosition().toPoint()
            elif event.position().toPoint().y() < 40:  # 在标题栏区域
                self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
    
    def mouseMoveEvent(self, event):
        """鼠标移动事件 - 拖动窗口或拉伸窗口"""
        if self.resizing and self.resize_edge:
            self.resize_window(event.globalPosition().toPoint())
        elif event.buttons() == Qt.MouseButton.LeftButton and not self.drag_position.isNull():
            if event.position().toPoint().y() < 40 and not self.isMaximized():  # 拖动标题栏
                self.move(event.globalPosition().toPoint() - self.drag_position)
        else:
            # 更新鼠标光标形状
            edge = self.get_resize_edge(event.position().toPoint())
            if edge and not self.isMaximized():
                self.update_cursor(edge)
            else:
                self.setCursor(Qt.CursorShape.ArrowCursor)
    
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.resizing = False
            self.resize_edge = None
            self.drag_position = QPoint()
    
    def mouseDoubleClickEvent(self, event):
        """鼠标双击事件 - 双击标题栏最大化/还原"""
        if event.position().toPoint().y() < 40:  # 在标题栏区域
            self.toggle_maximize()
    
    def get_resize_edge(self, pos):
        """获取鼠标位置对应的窗口边缘"""
        rect = self.rect()
        margin = self.resize_margin
        
        left = pos.x() < margin
        right = pos.x() > rect.width() - margin
        top = pos.y() < margin
        bottom = pos.y() > rect.height() - margin
        
        if top and left:
            return 'top-left'
        elif top and right:
            return 'top-right'
        elif bottom and left:
            return 'bottom-left'
        elif bottom and right:
            return 'bottom-right'
        elif left:
            return 'left'
        elif right:
            return 'right'
        elif top:
            return 'top'
        elif bottom:
            return 'bottom'
        return None
    
    def update_cursor(self, edge):
        """根据边缘位置更新鼠标光标"""
        cursors = {
            'top': Qt.CursorShape.SizeVerCursor,
            'bottom': Qt.CursorShape.SizeVerCursor,
            'left': Qt.CursorShape.SizeHorCursor,
            'right': Qt.CursorShape.SizeHorCursor,
            'top-left': Qt.CursorShape.SizeFDiagCursor,
            'bottom-right': Qt.CursorShape.SizeFDiagCursor,
            'top-right': Qt.CursorShape.SizeBDiagCursor,
            'bottom-left': Qt.CursorShape.SizeBDiagCursor,
        }
        self.setCursor(cursors.get(edge, Qt.CursorShape.ArrowCursor))
    
    def resize_window(self, global_pos):
        """拉伸窗口"""
        delta = global_pos - self.drag_position
        rect = self.geometry()
        
        if 'left' in self.resize_edge:
            rect.setLeft(rect.left() + delta.x())
        if 'right' in self.resize_edge:
            rect.setRight(rect.right() + delta.x())
        if 'top' in self.resize_edge:
            rect.setTop(rect.top() + delta.y())
        if 'bottom' in self.resize_edge:
            rect.setBottom(rect.bottom() + delta.y())
        
        # 限制最小尺寸
        if rect.width() >= 600 and rect.height() >= 400:
            self.setGeometry(rect)
            self.drag_position = global_pos
    
    def set_style(self):
        """设置窗口样式"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #ecf0f1;
                border: 2px solid #3498db;
            }
            /* 标题栏样式 */
            #titleBar {
                background-color: #34495e;
                border-bottom: 1px solid #2c3e50;
            }
            /* 标签页按钮样式 */
            #tabButton {
                background-color: transparent;
                color: #ecf0f1;
                border: none;
                padding: 8px 20px;
                margin: 2px;
                font-size: 14px;
                border-radius: 0;
            }
            #tabButton:hover {
                background-color: #4a5f7f;
            }
            #tabButton:checked {
                background-color: #3498db;
                color: white;
                border-bottom: 3px solid #2980b9;
            }
            /* 窗口控制按钮样式 */
            #minimizeButton, #maximizeButton, #closeButton {
                background-color: transparent;
                color: #ecf0f1;
                border: none;
                font-size: 18px;
                font-weight: bold;
            }
            #minimizeButton:hover, #maximizeButton:hover {
                background-color: #4a5f7f;
            }
            #closeButton:hover {
                background-color: #e74c3c;
            }
            #minimizeButton:pressed, #maximizeButton:pressed {
                background-color: #2c3e50;
            }
            #closeButton:pressed {
                background-color: #c0392b;
            }
            QTabWidget::pane {
                border: none;
                background-color: white;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #1f618d;
            }
            QLineEdit {
                padding: 8px;
                border: 2px solid #bdc3c7;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #3498db;
            }
            QTextEdit {
                border: 2px solid #bdc3c7;
                border-radius: 4px;
                font-size: 14px;
            }
            QTableWidget {
                border: 1px solid #bdc3c7;
                gridline-color: #ecf0f1;
            }
            QHeaderView::section {
                background-color: #34495e;
                color: white;
                padding: 8px;
                border: none;
                font-weight: bold;
            }
            QStatusBar {
                background-color: #ecf0f1;
                color: #2c3e50;
            }
        """)
    
    def on_tab_changed(self, index):
        """标签切换事件"""
        tab_names = ["欢迎", "编辑器", "数据表格"]
        if 0 <= index < len(tab_names):
            self.status_bar.showMessage(f"当前标签页: {tab_names[index]}")


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用名称
    app.setApplicationName("QTabWidget Demo")
    
    # 创建并显示主窗口
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
